package com.moshme.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.moshme.common.exception.ServiceException;
import com.moshme.project.domain.File;
import com.moshme.project.domain.FileExample;
import com.moshme.project.domain.FileProject;
import com.moshme.project.domain.StageCheckFile;
import com.moshme.project.service.FileService;
import com.moshme.project.service.StageCheckFileService;
import com.moshme.project.mapper.StageCheckFileMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author 19803
* @description 针对表【stage_check_file(验收阶段表)】的数据库操作Service实现
* @createDate 2023-09-19 10:42:10
*/
@Service
public class StageCheckFileServiceImpl extends ServiceImpl<StageCheckFileMapper, StageCheckFile>
    implements StageCheckFileService{

    @Autowired
    private FileService fileService;

    @Value("${moshme.profile}")
    private String storagePath;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<String> upload(MultipartFile file, Long projectId) {
        LambdaQueryWrapper<StageCheckFile> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<StageCheckFile> eq = lambdaQueryWrapper.eq(StageCheckFile::getProjectId, projectId);
        StageCheckFile stageCheckFile = getOne(eq);
        String networkPath = fileService.upload(file, "项目验收阶段/" + projectId);
        List<String> fileList = new ArrayList<>();
        if (stageCheckFile != null) {
            List<String> oldFileList = stageCheckFile.getFileList();
            for (String filePath : oldFileList) {
                fileList.add(filePath);
            }
            fileList.add(networkPath);
            stageCheckFile.setFileList(fileList);
            update(stageCheckFile, eq);
        } else {
            fileList.add(networkPath);
            StageCheckFile newStageCheckFile = new StageCheckFile();
            newStageCheckFile.setProjectId(projectId);
            newStageCheckFile.setFileList(fileList);
            save(newStageCheckFile);
        }
        return fileList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean delFile(Long projectId, String path) {
        LambdaQueryWrapper<File> fileLambdaQueryWrapper = new LambdaQueryWrapper<>();
        File file = fileService.getOne(fileLambdaQueryWrapper.eq(File::getNetworkPath, path));
        if (file == null) {
            throw new ServiceException("文件不存在");
        }
        fileService.remove(fileLambdaQueryWrapper.eq(File::getNetworkPath, path));
        LambdaQueryWrapper<StageCheckFile> stageCheckFileLambdaQueryWrapper = new LambdaQueryWrapper<>();
        StageCheckFile stageCheckFile = getOne(stageCheckFileLambdaQueryWrapper.eq(StageCheckFile::getProjectId, projectId));
        List<String> fileList = new ArrayList<>();
        fileList.addAll(stageCheckFile.getFileList());
        if (fileList != null) {
            if (fileList.size() != 1) {
                List<String> list = fileList.stream().filter((String s) -> !s.equals(path)).collect(Collectors.toList());
                stageCheckFile.setFileList(list);
                update(stageCheckFile, stageCheckFileLambdaQueryWrapper.eq(StageCheckFile::getProjectId, projectId));
            } else {
                remove(stageCheckFileLambdaQueryWrapper.eq(StageCheckFile::getProjectId, projectId));
            }
        }
        java.io.File ioFile = new java.io.File(file.getLocalPath());
        if (ioFile.exists()) {
            if (!ioFile.delete()) {
                throw new ServiceException("文件删除失败");
            }
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean delAllFile(Long projectId){
        String filePath = storagePath + "/项目验收阶段/" + projectId+ "/";
        java.io.File file = new java.io.File(filePath);
        if (file.exists()){
            LambdaUpdateWrapper<StageCheckFile> stageCheckFileLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            remove(stageCheckFileLambdaUpdateWrapper.eq(StageCheckFile::getProjectId,projectId));
            LambdaUpdateWrapper<File> fileLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            fileService.remove(fileLambdaUpdateWrapper.like(File::getNetworkPath,"/profile/项目验收阶段/" + projectId));
            Path path = Paths.get(filePath);
            try {
                Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
                    // 先去遍历删除文件
                    @Override
                    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                        Files.delete(file);
                        return FileVisitResult.CONTINUE;
                    }

                    // 再去遍历删除目录
                    @Override
                    public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                        Files.delete(dir);
                        return FileVisitResult.CONTINUE;
                    }

                });
            } catch (IOException e) {
                throw new ServiceException("文件删除失败");
            }
        }
        return true;
    }
}




